package com.icloud.system.boot.service.impl;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.icloud.common.database.mapper.AppCustomerAuthMapper;
import com.icloud.system.boot.service.GoogleAuthenticatorService;
import com.warrenstrange.googleauth.GoogleAuthenticator;
import com.warrenstrange.googleauth.GoogleAuthenticatorKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import java.io.IOException;

@Slf4j
@Service
public class GoogleAuthenticatorServiceImpl implements GoogleAuthenticatorService {
    private static final String KEY_FORMAT = "otpauth://totp/%s?secret=%s";
    private static final String IMAGE_EXT = "png";
    private static final int WIDTH = 300;
    private static final int HEIGHT = 300;
    @Autowired
    private GoogleAuthenticator googleAuthenticator;
    @Autowired
    private AppCustomerAuthMapper appCustomerAuthMapper;

    /**
     * 生成二维码链接
     */
    public String getQrUrl(String username) {
        //调用createCredentials都会生成新的secretKey
        GoogleAuthenticatorKey key = googleAuthenticator.createCredentials(username);
        return String.format(KEY_FORMAT, username, key.getKey());
    }
    /**
     * 验证code
     */
    public boolean validCode(String username, int code) {
        return googleAuthenticator.authorizeUser(username, code);
    }
    /**
     * 生成二维码
     */
    public void genQRImage(String username, ServletOutputStream stream) {
        try {
            String content = getQrUrl(username);
            BitMatrix bm = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT);
            MatrixToImageWriter.writeToStream(bm, IMAGE_EXT, stream);
        } catch (WriterException | IOException e) {
            log.error("生成二维码异常",e);
        }
    }
}
